  <template>
    <div>
      <Dialog
        :show="dialogConfig.show"
        :title="dialogConfig.title"
        :buttons="dialogConfig.buttons"
        :showCancel="false"
        @close="closeDialog"
      >
        <el-form
          class="login-register"
          :model="formData"
          :rules="rules"
          ref="formDataRef"
        >
          <!--input输入-->
          <el-form-item prop="email">
            <el-input
              v-model="formData.email"
              size="large"
              clearable
              maxlength="150"
              placeholder="请输入邮箱"
            >
              <template #prefix>
                <span class="iconfont icon-account"></span>
              </template>
            </el-input>
          </el-form-item>
          <!-- 登录密码 -->
          <el-form-item
            prop="password"
            v-if="opType == 1"
          >
            <el-input
              show-password
              v-model="formData.password"
              size="large"
              clearable
              placeholder="请输入密码"
            >
              <template #prefix>
                <span class="iconfont icon-password"></span>
              </template>
            </el-input>
          </el-form-item>
          <!-- 注册 -->
          <div v-if="opType == 0 || opType == 2">
            <el-form-item prop="emailCode">
              <div class="send-email-panel">
                <el-input
                  v-model="formData.emailCode"
                  size="large"
                  clearable
                  placeholder="请输入邮箱验证码"
                >
                  <template #prefix>
                    <span class="iconfont icon-checkcode"></span>
                  </template>
                </el-input>
                <el-button
                  class="send-email-btn"
                  type="primary"
                  size="large"
                  @click="getEmailCode()"
                >获取验证码</el-button>
              </div>
              <el-popover
                placement="left"
                trigger="click"
                :width="500"
                popper-style="box-shadow: rgb(14 18 22 / 35%) 0px 10px 38px -10px, rgb(14 18 22 / 20%) 0px 10px 20px -15px; padding: 20px;"
              >
                <div>
                  <p>1、在垃圾箱中寻找邮箱验证码</p>
                  <p>2、在邮箱中 头像->设置->反垃圾->白名单->设置邮件地址白名单</p>
                  <p>3、将邮箱【2086155836@qq.com】添加到白名单 不知道怎么设置？</p>
                </div>
                <template #reference>
                  <span
                    class="a-link"
                    style="font-size: 14px;"
                  >未收到邮箱验证码?</span>
                </template>
              </el-popover>
            </el-form-item>
            <el-form-item
              v-if="opType == 0"
              prop="nickName"
            >
              <el-input
                v-model="formData.nickName"
                size="large"
                clearable
                maxlength="20"
                placeholder="请输入昵称"
              >
                <template #prefix>
                  <span class="iconfont icon-account"></span>
                </template>
              </el-input>
            </el-form-item>
            <el-form-item prop="registerPassword">
              <el-input
                v-model="formData.registerPassword"
                size="large"
                clearable
                placeholder="请输入密码"
              >
                <template #prefix>
                  <span class="iconfont icon-password"></span>
                </template>
              </el-input>
            </el-form-item>
            <el-form-item prop="reRegisterPassword">
              <el-input
                show-password
                v-model="formData.reRegisterPassword"
                size="large"
                clearable
                placeholder="请再次输入密码"
              >
                <template #prefix>
                  <span class="iconfont icon-password"></span>
                </template>
              </el-input>
            </el-form-item>
          </div>
          <el-form-item prop="checkCode">
            <div class="check-code-panel">
              <el-input
                v-model="formData.checkCode"
                size="large"
                clearable
                @keyup.enter="doSubmit"
                placeholder="请输入验证码"
              >
                <template #prefix>
                  <span class="iconfont icon-checkcode"></span>
                </template>
              </el-input>
              <img
                :src="checkCodeUrl"
                class="check-code"
                @click="changeCheckCode(0)"
              >
            </div>
          </el-form-item>
          <el-form-item v-if="opType == 1">
            <div class="remeberMe-panel">
              <el-checkbox v-model="formData.rememberMe">记住我</el-checkbox>
            </div>
            <div class="no-account">
              <a
                href="javascript:void(0)"
                @click="showPanel(2)"
              >忘记密码?</a>
              <a
                href="javascript:void(0)"
                @click="showPanel(0)"
              >没有账号</a>
            </div>
          </el-form-item>
          <el-form-item v-if="opType == 0">
            <div class="no-account">
              <a
                href="javascript:void(0)"
                @click="showPanel(1)"
              >已有账号?</a>
            </div>
          </el-form-item>
          <el-form-item v-if="opType == 2">
            <div class="no-account">
              <a
                href="javascript:void(0)"
                @click="showPanel(1)"
              >去登录</a>
            </div>
          </el-form-item>
          <el-form-item>
            <el-button
              class="op-btn"
              type="primary"
              size="default"
              @click="doSubmit"
            >
              <span v-if="opType == 0">注册</span>
              <span v-if="opType == 1">登录</span>
              <span v-if="opType == 2">重置密码</span>
            </el-button>
          </el-form-item>
        </el-form>
      </Dialog>
      <Dialog
        :show="dialogConfig4SendMailCode.show"
        :title="dialogConfig4SendMailCode.title"
        :buttons="dialogConfig4SendMailCode.buttons"
        width="500px"
        :showCancel="false"
        @close="dialogConfig4SendMailCode.show = false"
      >
        <el-form
          :model="formData4SendMailCode"
          :rules="rules"
          ref="formData4SendMailCodeRef"
          label-width="80px"
          @submit.prevent
        >
          <el-form-item label="邮箱">
            {{ formData.email }}
          </el-form-item>
          <!--input输入-->
          <el-form-item
            label="验证码"
            prop="checkCode"
            required="true"
          >
            <div class="check-code-panel">
              <el-input
                v-model="formData4SendMailCode.checkCode"
                size="large"
                clearable
                placeholder="请输入验证码"
                @keyup.enter="doSubmit"
              >
                <template #prefix>
                  <span class="iconfont icon-checkcode"></span>
                </template>
              </el-input>
              <img
                :src="checkCodeUrl4SendMailCode"
                class="check-code"
                @click="changeCheckCode(1)"
              >
            </div>
          </el-form-item>

        </el-form>
      </Dialog>

    </div>
  </template>

<script setup>
import { dialogProps, messageConfig } from 'element-plus';
import md5 from 'js-md5';
import { ref, reactive, getCurrentInstance, nextTick } from 'vue';
import { useRoute, useRouter } from 'vue-router'
import { useStore } from 'vuex';
const { proxy } = getCurrentInstance();
const route = useRoute();
const router = useRouter();
const store = useStore();

const api = {
  checkCode: '/api/checkCode',
  sendMailCode: '/sendEmailCode',
  register: '/register',
  login: '/login',
  resetPwd: '/resetPwd',
}

// 0:注册 1:登录 2:重置密码
const opType = ref();
const showPanel = (type) => {
  opType.value = type;
  resetForm();
}
defineExpose({ showPanel });

//验证码
const checkCodeUrl = ref(api.checkCode);
const checkCodeUrl4SendMailCode = ref(api.checkCode)
const changeCheckCode = (type) => {
  if (type == 0) {
    checkCodeUrl.value = api.checkCode + "?type=" + type + "&time=" + new Date().getTime()
  } else if (type == 1) {
    checkCodeUrl4SendMailCode.value = api.checkCode + "?type=" + type + "&time=" + new Date().getTime()
  }

}

// 发送邮箱验证码弹窗
const dialogConfig4SendMailCode = reactive({
  show: false,
  title: "发送邮箱验证码",
  buttons: [
    {
      type: "primary",
      text: "发送验证码",
      click: () => {
        sendEmailCode();
      }
    }
  ]
});

const formData4SendMailCode = ref({
  email: '',
  checkCode: ''  // 确保 checkCode 字段被正确初始化
});
const formData4SendMailCodeRef = ref();

// 获取邮箱验证码
const getEmailCode = () => {
  formDataRef.value.validateField("email", (valid) => {
    if (!valid) {
      console.log("Email 格式无效或为空");
      // 如果验证失败，不做后续操作
      return;
    } else {
      // 如果验证通过，显示发送验证码的弹窗
      dialogConfig4SendMailCode.show = true;
    }
    nextTick(() => {
      changeCheckCode(1);
      formData4SendMailCodeRef.value.resetFields();
      formData4SendMailCode.value = {
        email: formData.value.email
      }
    })
  })
}

//发送邮件
const sendEmailCode = () => {
  formData4SendMailCodeRef.value.validate(async (valid) => {
    if (!valid) {
      return;
    }
    const params = Object.assign({}, formData4SendMailCode.value)
    params.type = 0 ? 0 : 1;
    let result = await proxy.Request({
      url: api.sendMailCode,
      params: params,
      errorCallback: () => {
        changeCheckCode(1);
      }
    });

    if (!result) {
      return;
    }

    proxy.Message.success("验证码发送成功，请前往邮箱查看")
    dialogConfig4SendMailCode.show = false;
  })
}

// 登录注册弹出框
const dialogConfig = reactive({
  show: false,
  title: "标题",
});

const checkRePassword = (rule, value, callback) => {
  if (value !== formData.value.registerPassword) {
    callback(new Error(rule.message))
  } else {
    callback();
  }
}



const formData = ref({
  email: '',
  emailCode: '',
});
const formDataRef = ref();
const rules = {
  email: [
    { required: true, message: "请输入邮箱" },
    { max: 150, message: "邮箱太长" },
    { validator: proxy.Verify.email, message: "请输入正确的邮箱" }
  ],
  password: [
    { required: true, message: "请输入密码" },

  ],
  emailCode: [
    { required: true, message: "请输入邮箱验证码" }
  ],
  nickName: [
    { required: true, message: "请输入昵称" }
  ],
  registerPassword: [
    { required: true, message: "请输入注册密码" },

  ],
  reRegisterPassword: [
    { required: true, message: "请输入注册密码" },
    {
      validator: checkRePassword,
      message: "两次输入的密码不一致"
    },
  ],
  checkCode: [
    { required: true, message: "请输入图片验证码" }
  ],
};

// 重置表单
const resetForm = () => {
  dialogConfig.show = true;
  if (opType.value == 0) {
    dialogConfig.title = "注册"
  } else if (opType.value == 1) {
    dialogConfig.title = "登录"
  } else if (opType.value == 2) {
    dialogConfig.title = "重置密码"
  }
  nextTick(() => {
    changeCheckCode(0);
    formDataRef.value.resetFields();
    formData.value = {
    }
    if (opType.value == 1) {
      const cookieLoginInfo = proxy.VueCookies.get("loginInfo")
      if (cookieLoginInfo) {
        formData.value = cookieLoginInfo
      }
    }
  })
}

//登录 注册 重置密码 提交表单
const doSubmit = () => {
  formDataRef.value.validate(async (valid) => {
    if (!valid) {
      return;
    }

    let params = {};
    Object.assign(params, formData.value);

    //注册 重置
    if (opType.value == 0 || opType.value == 2) {
      params.password = params.registerPassword
      delete params.registerPassword
      delete params.reRegisterPassword
    }

    // 登录
    if (opType.value == 1) {
      let cookieLoginInfo = proxy.VueCookies.get("loginInfo");
      let cookiePassword = cookieLoginInfo.password == null ? null : cookieLoginInfo.password
      if (params.password !== cookiePassword) {
        params.password = md5(params.password)
      }
    }

    let url = null;
    if (opType.value == 0) {
      url = api.register
    } else if (opType.value == 1) {
      url = api.login
    } else if (opType.value == 2) {
      url = api.resetPwd
    }

    let result = await proxy.Request({
      url: url,
      params: params,
      errorCallback: () => {
        changeCheckCode(0)
      }
    })
    if (!result) {
      return;
    }

    //注册返回
    if (opType.value == 0) {
      proxy.Message.success("注册成功，请前往登录")
      showPanel(1)
    }
    // 登录
    else if (opType.value == 1) {
      if (params.rememberMe) {
        const loginInfo = {
          email: params.email,
          password: params.password,
          rememberMe: params.rememberMe
        }
        proxy.VueCookies.set("loginInfo", loginInfo, "7d")
      } else {
        proxy.VueCookies.remove("loginInfo")
      }
      dialogConfig.show = false
      proxy.Message.success("登录成功！")
      store.commit("updateLoginUserInfo", result.data)
    }
    // 重置密码
    else if (opType.value == 2) {
      proxy.Message.success("重置成功，请前往登录")
      showPanel(1)
    }
  })
}

const closeDialog = () => {
  dialogConfig.show = false;
  store.commit('showLogin', false)
}
</script>

<style lang="scss" scoped>
.login-register {


  .remeberMe-panel {
    width: 100%;
  }

  .no-account {
    width: 100%;
    display: flex;
    justify-content: space-between;
  }

  .op-btn {
    width: 100%;
  }

  .send-email-panel {
    width: 100%;
    display: flex;

    .send-email-btn {
      margin-left: 5px;
    }
  }

  .a-link {
    text-decoration: none !important;
    color: var(--link) !important;
    cursor: pointer;
  }
}

.check-code-panel {
  display: flex;
  width: 100%;

  .check-code {
    width: 200px;
    margin-left: 5px;
    cursor: pointer;
  }
}
</style>
